package com.yinuo.face.user;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;

import com.bumptech.glide.Glide;
import com.raizlabs.android.dbflow.config.FlowManager;
import com.raizlabs.android.dbflow.sql.language.SQLite;
import com.raizlabs.android.dbflow.structure.ModelAdapter;
import com.yinuo.face.R;

import java.util.UUID;

/**
 * A login screen that offers login via email/password.
 */
public class UserActivity extends AppCompatActivity implements OnClickListener {

    private EditText userIdentifier;
    private EditText userName;
    private User user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user);
        // Set up the login form.
        userIdentifier = findViewById(R.id.user_identifier);

        userName = findViewById(R.id.user_name);
        ImageButton userHeader = findViewById(R.id.user_header);
        Button button_save = findViewById(R.id.button_save);
        Button button_cancel = findViewById(R.id.button_cancel);
        Button button_delete = findViewById(R.id.button_delete);

        button_delete.setOnClickListener(this);
        button_cancel.setOnClickListener(this);
        button_save.setOnClickListener(this);

        Intent intent = getIntent();
        String userId = intent.getStringExtra("userId");
        user = SQLite.select().from(User.class).where(User_Table.id.eq(UUID.fromString(userId))).limit(1).querySingle();
        if (user != null) {
            userIdentifier.setText(user.getUserIdentifier());
            userName.setText(user.getUserName());
            Glide.with(this).load(user.getUserHeader()).into(userHeader);
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.button_cancel) {
            finish();
        }
        if (v.getId() == R.id.button_save) {
            user.setUserName(userName.getText().toString());
            user.setUserIdentifier(userIdentifier.getText().toString());
            ModelAdapter<User> userModelAdapter = FlowManager.getModelAdapter(User.class);
            userModelAdapter.save(user);
            finish();
        }
        if (v.getId() == R.id.button_delete) {
            ModelAdapter<User> userModelAdapter = FlowManager.getModelAdapter(User.class);
            userModelAdapter.delete(user);
            finish();
        }
    }
}

